﻿var activeInstance = null;
var rootPath = '';

function ShowError(msg) {
    Ext.Msg.alert('StartFrame', msg);
}

function ForeignStoreRenderer(storeId, nombre) {
    return function (value, metaData, record, rowIndex, colIndex, store, view) {
        try {
            return Ext.StoreMgr.get(storeId).findRecord(this.columns[colIndex].dataIndex, value, 0, false, false, true).get(nombre);
        } catch (ex) {
            return '';
        }
    };
}

function CreateListFilter(labelField, valueField, storeId) {
    return {
        type: 'list',
        labelField: labelField,
        valueField: valueField,
        store: Ext.StoreMgr.get(storeId),
        phpMode: true
    };
}

function CreateForeignStore(storeId, model, autoLoad) {
    autoLoad = typeof autoLoad !== 'undefined' ? autoLoad : true;
    return Ext.create('Ext.data.Store', {
        storeId: storeId,
        autoLoad: autoLoad,
        model: model,
        pageSize: -1
    });
}

function CreateFirstEmptyStore(storeId, model) {
    return Ext.create('StartFrame.data.FirstEmptyStore', {
        storeId: storeId,
        autoLoad: true,
        model: model,
        pageSize: -1
    });
}

function login() {
    try {
        if (useIdentity === true)
            return;
    }
    catch (e) { }


    Ext.apply(Ext.form.field.VTypes, {
        pass: function (val, field) {
            return Ext.getCmp('tfNewPassword').getValue() == Ext.getCmp('tfNewRepeatPassword').getValue();
        },
        passText: 'Las claves tienen que ser iguales.'
    });

    if (Ext.getCmp('lnkLogin').getEl().dom.innerHTML.toLowerCase() == 'ingresar') {
        try {
            AntesLogueo();
        } catch (e) {

        }
        var winLogin = new Ext.create('Ext.window.Window', {
            id: 'winLogin',
            autoHeight: true,
            width: 400,
            layout: 'fit',
            autoDestroy: true,
            modal: true,
            closable: true,
            closeAction: 'destroy',
            items: [{
                xtype: 'form',
                layout: 'form',
                frame: true,
                id: 'formLogin',
                monitorValid: true,
                autoDestroy: true,
                bodyStyle: {
                    "padding-right": '20px'
                },
                buttons: [{
                    id: 'btnLoginAceptar',
                    text: 'Aceptar',
                    formBind: true,
                    handler: function () {
                        serverLogin(Ext.getCmp('formLogin').getValues().usuario, Ext.getCmp('formLogin').getValues().password);
                        winLogin.close();
                    }
                }],
                items: [{
                    id: 'tfUsuario',
                    xtype: 'textfield',
                    fieldLabel: 'Usuario',
                    name: 'usuario',
                    maxLength: 50,
                    enforceMaxLength: true,
                    allowBlank: false
                }, {
                    xtype: 'textfield',
                    fieldLabel: 'Clave',
                    name: 'password',
                    maxLength: 50,
                    enforceMaxLength: true,
                    allowBlank: false,
                    inputType: 'password'
                }, {
                    id: 'tfNewPassword',
                    xtype: 'textfield',
                    fieldLabel: 'Nueva Clave',
                    name: 'newpassword',
                    maxLength: 50,
                    enforceMaxLength: true,
                    allowBlank: false,
                    inputType: 'password',
                    hidden: true,
                    disabled: true,
                    vtype: 'pass'
                }, {
                    id: 'tfNewRepeatPassword',
                    xtype: 'textfield',
                    fieldLabel: 'Repetir Clave',
                    name: 'newrepeatpassword',
                    maxLength: 50,
                    enforceMaxLength: true,
                    allowBlank: false,
                    inputType: 'password',
                    hidden: true,
                    disabled: true,
                    vtype: 'pass'
                }]
            }]
        });
        winLogin.show();
        var map = new Ext.util.KeyMap({
            target: winLogin.getEl(),
            binding: [{
                key: [10, 13],
                fn: function () {
                    if (Ext.getCmp('formLogin').getForm().isValid()) {
                        Ext.getCmp('btnLoginAceptar').handler();
                    }
                }
            }]
        });
        Ext.defer(function () { Ext.getCmp('tfUsuario').focus() }, 100);
    } else {
        var response = Ext.Ajax.request({
            async: false,
            url: 'Handlers/LoginHandler.ashx',
            params: {
                action: 'salir'
            }
        });
        var result = Ext.JSON.decode(response.responseText);
        if (result.success) {
            document.location.reload();
        }
    }
}

function serverLogin(usuario, password) {
    var response = Ext.Ajax.request({
        async: false,
        url: 'Handlers/LoginHandler.ashx',
        params: {
            action: 'ingresar',
            usuario: usuario,
            password: password
        }
    });
    var result = Ext.JSON.decode(response.responseText);
    if (result.success) {
        Ext.getCmp('lnkLogin').update('<img src="Resources/images/Log%20Out.png" />&nbsp;' + usuario);
        try {
            if (useIdentity === true) {
                Ext.getCmp('lnkLogin').setDisabled(true);
                Ext.getCmp('lnkLogin').unmask();
            }
        } catch (e) { }
        Ext.getCmp('navigationTree').getRootNode().expand();
        try {
            ComprobarNovedades();
            DespuesLogueo();
        } catch (e) { }
    } else {
        if (result.changePassword) {
            Ext.getCmp('tfUsuario').setReadOnly(true);
            Ext.getCmp('tfNewPassword').setVisible(true);
            Ext.getCmp('tfNewPassword').setDisabled(false);
            Ext.getCmp('tfNewRepeatPassword').setVisible(true);
            Ext.getCmp('tfNewRepeatPassword').setDisabled(false);
        }
        ShowError(result.message);
    }
}

Ext.onReady(function () {
    Ext.tip.QuickTipManager.init();
    Ext.create('Ext.container.Viewport', {
        layout: 'border',
        items: [Ext.create('Ext.tree.Panel', {
            id: 'navigationTree',
            region: 'west',
            collapsible: true,
            title: 'Navigation',
            split: true,
            minWidth: 150,
            width: 150,
            rootVisible: false,
            listeners: {
                select: function (rModel, record, index, eOpts) {
                    if (!Ext.isEmpty(record.data.url)) {
                        Ext.getCmp('mainPanel').removeAll(true);
                        var objClass;
                        try {
                            Ext.getBody().mask('Cargando, Por favor espere...');
                            Ext.Ajax.request({
                                url: record.data.url,
                                params: {
                                    action: 'CargarPagina'
                                },
                                success: function (response) {
                                    var text = response.responseText;
                                    objClass = eval(text);

                                    Ext.getCmp('pnlInformacion').update(record.raw.qtip);
                                    Ext.destroy(activeInstance);
                                    activeInstance = objClass.create();
                                    if (!Ext.isEmpty(record.data.iconCls)) {
                                        activeInstance.Icon = record.data.iconCls;
                                    }
                                    Ext.getCmp('mainPanel').add(activeInstance.init());
                                    Ext.getBody().unmask();
                                },
                                failure: function () {
                                    Ext.getBody().unmask();
                                }
                            });
                        } catch (e) {
                            ShowError('Ocurrio un error cargando el formulario.');
                            return;
                        }

                    }
                }
            },
            store: Ext.create('Ext.data.TreeStore', {
                autoLoad: false,
                proxy: {
                    type: 'ajax',
                    url: 'Handlers/Menu.ashx',
                    reader: 'json'
                },
                root: {
                    text: 'rootMenu',
                    id: -2
                },
                fields: [
                                    { name: 'id', type: 'int' },
                                    { name: 'text', type: 'string' },
                                    { name: 'url', type: 'string' }
                ]
            })
        })
                        , {
                            id: 'mainNorthPanel',
                            region: 'north',
                            height: 60,
                            collapsible: false,
                            border: false,
                            layout: 'hbox',
                            bodyStyle: {
                                'background': 'url(resources/images/bg-top.gif) repeat-x'
                            },
                            items: [{
                                xtype: 'container',
                                flex: 1,
                                items: [{
                                    xtype: 'image',
                                    height: 35,
                                    src: 'resources/images/StartFrame_transparente.png'
                                }]
                            }, {
                                xtype: 'component',
                                id: 'lnkLogin',
                                autoEl: {
                                    tag: 'a',
                                    onclick: 'login();',
                                    href: '#',
                                    html: 'Ingresar'
                                }
                            }]
                        }, {
                            region: 'east',
                            xtype: 'panel',
                            id: 'pnlBandeja',
                            title: 'Bandeja de Entrada',
                            collapsible: true,
                            collapsed: false,
                            split: true,
                            width: 150
                        }, {
                            region: 'center',
                            id: 'mainPanel',
                            layout: 'fit',
                            xtype: 'panel'
                        }, {
                            region: 'south',
                            id: 'pnlInformacion',
                            title: 'Información',
                            collapsible: true,
                            split: true,
                            height: 100,
                            minHeight: 100
                        }]
    });
    login();
});


Ext.define('Ext.ux.CheckColumn', {
    extend: 'Ext.grid.column.Column',
    alias: 'widget.checkcolumn',
    stopSelection: true,
    tdCls: Ext.baseCSSPrefix + 'grid-cell-checkcolumn',
    constructor: function () {
        this.addEvents(
            'beforecheckchange',
            'checkchange'
        );
        this.callParent(arguments);
    },
    processEvent: function (type, view, cell, recordIndex, cellIndex, e, record, row) {
        var me = this,
            key = type === 'keydown' && e.getKey(),
            mousedown = type == 'mousedown';

        if (mousedown || (key == e.ENTER || key == e.SPACE)) {
            var dataIndex = me.dataIndex,
                checked = !record.get(dataIndex);
            if (me.fireEvent('beforecheckchange', me, recordIndex, checked) !== false) {
                record.set(dataIndex, checked);
                me.fireEvent('checkchange', me, recordIndex, checked);
                if (mousedown) {
                    e.stopEvent();
                }
                if (!me.stopSelection) {
                    view.selModel.selectByPosition({
                        row: recordIndex,
                        column: cellIndex
                    });
                }
                return false;
            } else {
                return !me.stopSelection;
            }
        } else {
            return me.callParent(arguments);
        }
    },
    renderer: function (value) {
        var cssPrefix = Ext.baseCSSPrefix,
            cls = [cssPrefix + 'grid-checkheader'];
        if (value) {
            cls.push(cssPrefix + 'grid-checkheader-checked');
        }
        return '<div class="' + cls.join(' ') + '">&#160;</div>';
    }
});
